/**
 * 包含所有的action creator
 * 异步
 * 同步
 */
import Cookies from "js-cookie";

import { isSuccess, localStorage } from "../api/ajax";
import { reqLogin, reqRegister, reqAutoLogin } from "../api/index"
import { AUTH_SUCCESS, ERROR_MESSAGE, AUTH_FAILED } from "./action-types";

//登陆成功同步ACTION
export const authSuccess = (user) => ({ type: AUTH_SUCCESS, data: user })
export const authFailed = (message) => ({ type: AUTH_FAILED, data: message })
export const errorMessage = (message) => ({ type: ERROR_MESSAGE, data: message })


//异步请求登陆
export const login = ({ userName, password }) => {
    console.log("actions: login -> ", { userName, password })
    return async dispatch => {
        var response = await reqLogin({ userName, password });
        if (isSuccess(response)) {
            var user = response.data.data
            localStorage.setItem("token", user.token)
            Cookies.set('token', user.token)
            dispatch(authSuccess(user))
        } else {
            dispatch(authFailed(response.data.message))
        }
    }
}

//异步请求注册
export const register = ({ userName, password }) => {
    console.log("actions: register -> ", { userName, password })
    return async dispatch => {
        var response = await reqRegister({ userName, password });
        if (isSuccess(response)) {
            var user = response.data.data
            localStorage.setItem("token", user.token)
            Cookies.set('token', user.token)
            dispatch(authSuccess(user))
        } else {
            dispatch(authFailed(response.data.message))
        }
    }
}

//异步请求注册
export const autoLogin = (token) => {
    return async dispatch => {
        var response = await reqAutoLogin(token);
        if (isSuccess(response)) {
            var user = response.data.data
            localStorage.setItem("token", user.token)
            Cookies.set('token', user.token)
            dispatch(authSuccess(user))
        } else {
            dispatch(authFailed(response.data.message))
        }
    }
}

